package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
<<<<<<< HEAD
import com.itheima.dao.OrderDao;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.*;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.AddressDao;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.utils.DateUtils;


import java.util.Date;
import java.util.Map;

@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private AddressDao addressDao;

    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) throws Exception {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        Date[] dates = queryPageBean.getDates();
        String startdate1 = null;
        String enddate1 = null;
        if (dates != null && dates.length > 0) {
            Date date1 = dates[0];
            Date date2 = dates[1];
            startdate1 = DateUtils.parseDate2String(date1);
            enddate1 = DateUtils.parseDate2String(date2);
        }

        String orderType = queryPageBean.getOrderType();
        if ("".equals(orderType)) {
            orderType = null;
        }
        String orderStatus = queryPageBean.getOrderStatus();
        if ("".equals(orderStatus)) {
            orderStatus = null;
        }
        String setmealName = queryPageBean.getSetmealName();
        if ("".equals(setmealName)) {
            setmealName = null;
        }
        String nameOrPhoneNum = queryPageBean.getQueryString();
        if ("".equals(nameOrPhoneNum)) {
            nameOrPhoneNum = null;
        }
        Date startdate = DateUtils.parseString2Date(startdate1);
        Date enddate = DateUtils.parseString2Date(enddate1);
        Page<Map<String, Object>> page = orderDao.findByCondition(startdate, enddate, orderType, orderStatus, setmealName, nameOrPhoneNum);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public List<String> findAllSetmealName() {
        return orderDao.findAllSetmealName();
    }

    @Override
    public List<Setmeal> findAll() {
        return orderDao.findAll();
    }

    @Override
    public Result add(OrderInfo orderInfo, Integer[] setmealIds) throws Exception {
        //1.检查用户所选择的预约日期是否已经提前设置了预约设置,如果没有设置则无法进行预约
        Date orderDate = orderInfo.getOrderDate();
        String date = DateUtils.parseDate2String(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(date));
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2.检查当日预约日期的预约认识是否已经约满,如果约满,则无法预约
        int reservations = orderSetting.getReservations();//已预约人数
        int number = orderSetting.getNumber();//可预约人数
        if (reservations >= number) {
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //3.检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String phoneNumber = orderInfo.getPhoneNumber();
        Member member = memberDao.findByPhoneNumber(phoneNumber);
        //如果为会员,则不进行静默注册,需要判断同一天是否预约了同一个套餐
        if (member != null) {
            if (setmealIds != null && setmealIds.length > 0) {
                for (Integer setmealId : setmealIds) {
                    Integer memberId = member.getId();
                    Date orderDate1 = DateUtils.parseString2Date(date);
                    Order order = new Order(memberId, orderDate1, setmealId);
                    //根据多条件查询预约信息
                    List<Order> orderlist = orderDao.findOrderInfoByCondition(order);
                    if (orderlist != null && orderlist.size() > 0) {
                        //在同一天查到了用一个会员用户的同一个套餐,说明已经存在该套餐,不能再次预约
                        return new Result(false, MessageConstant.HAS_ORDERED);
                    }
                }
            }
        }
        //如果会员表中没有该会员,说明是新用户,不存在重复预约,但是此处需要做一个静默注册
        if (member == null) {
            member = new Member();
            member.setName(orderInfo.getName());
            member.setRegTime(orderInfo.getOrderDate());
            member.setPhoneNumber(orderInfo.getPhoneNumber());
            memberDao.add(member);
            Integer id = member.getId();
        }

        //预约成功,更新当日的已预约人数
        if (setmealIds != null && setmealIds.length > 0) {
            for (Integer setmealId : setmealIds) {
                Order order = new Order();
                order.setMemberId(member.getId());
                order.setOrderDate(DateUtils.parseString2Date(date));
                order.setOrderType(orderInfo.getOrderType());
                order.setOrderStatus(Order.ORDERSTATUS_NO);
                order.setSetmealId(setmealId);
                orderDao.add(order);
            }
        }
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDER_SUCCESS);
    }

    @Override
    public Map<String, Object> findById(Integer id) {
        return orderDao.findById(id);
    }

    @Override
    public List<Integer> findSetmealById(Integer id) {
        return orderDao.findSetmealById(id);
    }

    @Override
    public Result edit(Order order, Integer[] setmealIds) {
        //进行编辑是要判断该用户修改之后,当天是否有同样的套餐消息,如果没有则可以修改,如果有则给用户一个提示
        // System.out.println(order.toString());
        //Integer memberId = order.getMemberId();
        Integer setmeal = setmealIds[0];
        //Date orderDate = order.getOrderDate();
        order.setSetmealId(setmeal);
        //根据多条件查询预约信息
        List<Order> orderlist = orderDao.findOrderInfoByCondition(order);
        if (orderlist != null && orderlist.size() > 0) {
            //在同一天查到了用一个会员用户的同一个套餐,说明已经存在该套餐,不能再次预约
            return new Result(false, MessageConstant.HAS_ORDERED);
        }
        //如果改天没有预约相同的套餐信息,则可以修改
        //order.setSetmealId(setmeal);
        orderDao.edit(order);
        return new Result(true, MessageConstant.EDIT_ORDER_SUCCESS);
    }

    @Override
    public void delete(Integer id) {
        orderDao.delete(id);
    }

    @Override
    public void updateStatus(Integer id) {
        Order order = orderDao.findOrderStatusById(id);
        String orderStatus2 = order.getOrderStatus();
        orderDao.updateOrderStatus(id,orderStatus2);
    }


    @Override
    public Result order(Map map) throws Exception {
//      1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting == null){
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
//      2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
            //获取可预约人数
        int number = orderSetting.getNumber();
            //获取已预约人数
        int reservations = orderSetting.getReservations();
        if (reservations >= number){
            //已经约满
            return new Result(false, MessageConstant.ORDER_FULL);
        }
//      3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);
        if (member != null){
            Integer memberId = member.getId();
            Date date = DateUtils.parseString2Date(orderDate);
            String setmealId = (String) map.get("setmealId");
            Order order = new Order(memberId,date, Integer.parseInt(setmealId));
            List<Order> list = orderDao.findByCondition(order);
            if(list != null && list.size() > 0){
                //说明重复预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        }else{
            // 4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }

//      5、预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(DateUtils.parseString2Date(orderDate));
        order.setOrderType((String) map.get("orderType"));
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));
        orderDao.add(order);

        //更新体检机构地址
        String longitudeAndLatitude = (String) map.get("longitudeAndLatitude");
        //查询该地址对应的id
        Integer orderId = order.getId();
        Integer addressId = addressDao.findId(longitudeAndLatitude);
        addressDao.setOrderIdAndAddressId(orderId,addressId);
        //更新已预约人数
        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDER_SUCCESS,order.getId());
    }

    /**
     * 根据预约Id查询预约信息(体检人姓名,预约日期,套餐名称,预约类型)
     * @param id
     * @return
     */
    @Override
    public Map findById(Integer id) throws Exception {
        Map map = orderDao.findById4Detail(id);
        if (map != null){
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate", DateUtils.parseDate2String(orderDate));
        }
        return map;
    }

    public List<Integer> findOrderByDate(List<String> months) {
        List<Integer> orderCount = new ArrayList<>();
        for (String month : months) {
            Integer order = orderDao.findOrderCountByDate(month);
            orderCount.add(order);
        }
        return orderCount;
    }

    public List<Integer> findReachByDate(List<String> months) {
        List<Integer> orderCount = new ArrayList<>();
        for (String month : months) {
            Integer visits = orderDao.findVisitsCountByDate(month);
            orderCount.add(visits);
        }
        return orderCount;
    }


    public List<Integer> findSetmealIdByDate(List<String> months) {
        List<Integer> orderCount = new ArrayList<>();
        for (String month : months) {
            List<Integer> reach = orderDao.findSetmealIdByDate(month);
            orderCount.addAll(reach);
        }
        return orderCount;
    }

    @Override
    public List<Integer> findSetmealData(String start, String end) {
        return orderDao.findSetmealData(start, end);
    }

}
